package com.dianban.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 接口拦截器
 *
 * @author wujh
 * @create 2020/1/10
 */
public class ApiInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(ApiInterceptor.class);

    private static final ThreadLocal<Long> startTimeThreadLocal =
            new NamedThreadLocal<Long>("ThreadLocal StartTime");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String sessionId = request.getSession().getId();
        logger.info("请求路径[" + sessionId + "][" + request.getRequestURI() + "] ");
        Map<String,String> hearderMap = new HashMap<String,String>();
        // 拿到所有请求头
        Enumeration headerEnume = request.getHeaderNames();
        while (headerEnume.hasMoreElements()) {
            String headerName = (String) headerEnume.nextElement();
            String headValue = request.getHeader(headerName);
            hearderMap.put(headerName, headValue);
        }
        logger.info("请求头参数[" + sessionId + "][" + JSONObject.toJSON(hearderMap) + "] ");
        logger.info("请求参数[" + sessionId + "][" + JSONObject.toJSON(request.getParameterMap()) + "]");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
